package org.inter.fsb.service.impl;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import org.inter.fsb.controller.BaseController;
import org.inter.fsb.service.CodeService;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@org.springframework.stereotype.Service
public class CodeServiceImpl implements CodeService {

    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${autor}")
    private String author;


    @Override
    public void codeGenerator(Map map) {
        DataSourceConfig.Builder DATA_SOURCE_CONFIG = new DataSourceConfig
                .Builder(jdbcUrl + "&rewriteBatchedStatements=true", username, password);
        String projectPath = System.getProperty("user.dir");

        FastAutoGenerator.create(DATA_SOURCE_CONFIG)
                // 全局配置
                .globalConfig((scanner, builder) -> builder.author(author)
                        .enableSwagger()
                        .fileOverride().outputDir(projectPath+"/src/main/java/"))
                // 包配置
                .packageConfig((scanner, builder) -> builder.parent("org.inter.fsb"))
                .templateConfig(builder -> builder.controller("/templates/controller.java"))
                .injectionConfig(consumer->{
                    Map<String, Object> cfg = new HashMap<>();
                    cfg.put("myTitle", "功能");
                    cfg.put("describe",map.get("describe").toString());
                    HashMap customMap = new HashMap<>();
                    customMap.put("cfg",cfg);
                    consumer.customMap(customMap).build();
                })
                // 策略配置
                .strategyConfig(builder -> builder.addInclude(map.get("tableName").toString()).controllerBuilder()
                                .superClass(BaseController.class).formatFileName("%sController")



//                        .enableHyphenStyle()
//                        .enableRestStyle()
                )
//
//                    模板引擎配置，默认 Velocity 可选模板引擎 Beetl 或 Freemarker
//                   .templateEngine(new BeetlTemplateEngine())
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }

    @Override
    public void code() {
        System.out.println(username);
        System.out.println(password);
        System.out.println(jdbcUrl);
        System.out.println(author);
    }

    @Override
    public void generatorVUE(Map map) {
        Configuration configuration = new Configuration(new Version("2.3.3"));
        configuration.setDefaultEncoding("utf-8");
        String absolutePath = System.getProperty("user.dir") + File.separator+"src" +
                File.separator + "main" + File.separator + "resources"+File.separator +"templates";
        try{
            // 加载.ftl配置文件所在路径
            configuration.setDirectoryForTemplateLoading(new File(absolutePath));

            // 放模板变量的值
            Map<String, Object> params = new HashMap<>();

            String name = map.get("name").toString();
            String searchChina = map.get("searchChina").toString();
            String searchEnglish = map.get("searchEnglish").toString();
            String displayChina = map.get("displayChina").toString();
            String displayEnglish = map.get("displayEnglish").toString();

            List searchList = new ArrayList();
            List displayList = new ArrayList();

            String[] splitSearchChina = searchChina.split(",");
            String[] splitSearchEnglish = searchEnglish.split(",");
            for (int i = 0; i < splitSearchChina.length; i++) {
                Map map1 = new HashMap();
                map1.put("china",splitSearchChina[i]);
                map1.put("english",splitSearchEnglish[i]);
                searchList.add(map1);
            }
            String[] splitDisplayChina = displayChina.split(",");
            String[] splitDisplayEnglish = displayEnglish.split(",");
            for (int i = 0; i < splitDisplayChina.length; i++) {
                Map map1 = new HashMap();
                map1.put("china",splitDisplayChina[i]);
                map1.put("english",splitDisplayEnglish[i]);
                displayList.add(map1);
            }
            params.put("name",name);
            params.put("searchList",searchList);
            params.put("displayList",displayList);

            //给文件赋值
            Template template = configuration.getTemplate("web.vue.ftl");
            // 文件输出路径
            FileOutputStream file = new FileOutputStream(System.getProperty("user.dir") + File.separator +"web.vue");
            OutputStreamWriter out = new OutputStreamWriter(file, "utf-8");
            template.process(params,out);
            out.close();
        }catch (IOException | TemplateException exception) {
            exception.printStackTrace();
        }
    }
}
